
let router = require('../router/Router');
let P = require("bluebird");
let Token = require('../token');
let cnst = require('../const');
let redis = require('../dao/redis');

let rankService = require('../service/rankService');
let cmService = require('../service/cmService');
let userService = require('../service/userService');

const { BusiError, SysError } = require('../exception/exception');

let avatar = require('../images');

let avatarMap = {
    cheers: [],
    animal: [],
    cartoon: [],
    honor: []
};

for (let i = 0; i < avatar.length; i++) {
    let item = avatar[i];
    if (item.indexOf("animal") !== -1){
        avatarMap.animal.push(item);
    } else if (item.indexOf("chicken") !== -1) {
        avatarMap.cheers.push(item);
    } else if (item.indexOf("cartoon") !== -1) {
        avatarMap.cartoon.push(item);
    } else if (item.indexOf("wangzhe") !== -1) {
        avatarMap.honor.push(item);
    }
}

router.post("/auth/avatar/list", (req, resp) => {
    if (!req.body.avatarType ||
        (req.body.avatarType !== "cartoon" &&
            req.body.avatarType !== "cheers" &&
            req.body.avatarType !== "honor" &&
            req.body.avatarType !== "animal")) {
        resp.send({code: 500, msg: "avatarType is available"});
        return;
    }

    let page = 1;
    if (req.body.page) {
        page = Number(req.body.page);
    }

    let cnt = avatarMap[req.body.avatarType].length;
    let start = (page - 1) * 30;
    let end = (page) * 30;
    if (end >= cnt) {
        end = cnt - 1;
    }

    let list = avatarMap[req.body.avatarType].slice(start, end);

    resp.send({
        code: 200, msg: "success", data: {
            data: list,
            cnt: cnt
        }
    });
});

router.jkAddCoin = P.coroutine(function* (req, res) {
    let token = req.query.token;
    let totalCoin = req.query.totalCoin;
    let addCoin = req.query.addCoin;//
    let roomId = req.query.roomId;
    let sign = req.query.sign;
    let gameType = req.query.gameType;
    let gameTime = req.query.gameTime;

    //add
    let clubid = req.query.clubid;
    let mode = req.query.mode;

    let s1 = "token=" + token;
    let s2 = "totalCoin=" + totalCoin;
    let s3 = "addCoin=" + addCoin;
    let s4 = "gameType=" + gameType;
    let s5 = "checkSign=" + cnst.checkSign;
    let s6 = "roomId=" + roomId;
    let s7 = "gameTime=" + gameTime;
    //addniu
    let s8 = "clubid=" + clubid;
    let s9 = "mode=" + mode;

    let ss = [s1, s2, s3, s4, s5, s6, s7, s8, s9];
    ss.sort(function (a, b) {
        if (a > b) {
            return 1;
        } else {
            return -1;
        }
    });
    let len = ss.length;
    let s = "";
    for (let i = 0; i < len; i++) {
        s = s + ss[i] + "&";
    }
    console.logg("sign str:", s);
    let md5 = Token.md5(s);
     if (md5 !== sign) {
        console.logg("invalid sign ", md5, sign);
        res.send({code: 500, msg: 'invalid sign'});
        return;
    }
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token);
        let uidObj = JSON.parse(uid);
        if (uidObj.uid){
            uid = uidObj.uid;
        }
    } catch (e) {
        uid = -1;
    }
    if (uid === -1 || uid == null) {
        console.logw('getGameInfo invalid uid');
        res.send({code: 500, msg: 'invalid uid'});
        return;
    }
    console.logw(uid, "玩家游戏中金额 ", totalCoin, " 增加", addCoin);

    // 上报数据到代理系统
    // try {
    //     yield cmService.saveOrder({uid: uid+"", amount: parseFloat(addCoin).toFixed(4)});
    // }catch (e) {
    //     console.logw("save order err:", e);
    // }

    yield userService.updateCoins(clubid, Number(mode), uid, gameType, addCoin, roomId, gameTime);

    res.send({code: 200, msg: 'success'});
});

router.get('/weixin/jkAddCoin', function (req, res) {
    router.jkAddCoin(req, res).catch(function (e) {
        console.logg("jkAddCoin exception ", e.message);
        if (!res.finished) {
            res.send({code: 500, msg: "exception"});
        }
    });
});


router.jkAddUnionCoin = P.coroutine(function* (req, res) {
    let token = req.query.token;
    let totalCoin = req.query.totalCoin;
    let addCoin = req.query.addCoin;//
    let roomId = req.query.roomId;
    let sign = req.query.sign;
    let gameType = req.query.gameType;
    let gameTime = req.query.gameTime;

    //add
    let clubid = req.query.clubid;
    let mode = req.query.mode;
    let unionid = req.query.unionid;

    let s1 = "token=" + token;
    let s2 = "totalCoin=" + totalCoin;
    let s3 = "addCoin=" + addCoin;
    let s4 = "gameType=" + gameType;
    let s5 = "checkSign=" + cnst.checkSign;
    let s6 = "roomId=" + roomId;
    let s7 = "gameTime=" + gameTime;
    //add
    let s8 = "clubid=" + clubid;
    let s9 = "mode=" + mode;
    let s10 = "unionid=" + unionid;

    let ss = [s1, s2, s3, s4, s5, s6, s7, s8, s9, s10];
    ss.sort(function (a, b) {
        if (a > b) {
            return 1;
        } else {
            return -1;
        }
    });
    let len = ss.length;
    let s = "";
    for (let i = 0; i < len; i++) {
        s = s + ss[i] + "&";
    }
    console.logg("sign str:", s);
    let md5 = Token.md5(s);
    if (md5 !== sign) {
        console.logg("invalid sign ", md5, sign);
        res.send({code: 500, msg: 'invalid sign'});
        return;
    }
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token);
        let uidObj = JSON.parse(uid);
        if (uidObj.uid){
            uid = uidObj.uid;
        }
    } catch (e) {
        uid = -1;
    }
    if (uid === -1 || uid == null) {
        console.logw('getGameInfo invalid uid');
        res.send({code: 500, msg: 'invalid uid'});
        return;
    }
    console.logw(uid, "玩家游戏中金额 ", totalCoin, " 增加", addCoin);

    yield userService.updateUnionCoins(unionid, clubid, Number(mode), uid, gameType, addCoin, roomId, gameTime);
    res.send({code: 200, msg: 'success'});
});

router.get('/weixin/jkAddUnionCoin', function (req, res) {
    router.jkAddUnionCoin(req, res).catch(function (e) {
        console.logg("jkAddCoin exception ", e.message);
        if (!res.finished) {
            res.send({code: 500, msg: "exception"});
        }
    });
});

router.post('/game/coins/update', (req, resp) => {
    // userService.updateCoins();
});

router.winCoinRecord = P.coroutine(function* (uid, name, totalCoin, addCoin, gameType, roomId, gameTime) {
    let d = new Date();
    yield userService.insertWinRecord(uid, name, totalCoin, addCoin, gameType, d, roomId, gameTime);
    let obj = {uid: uid, name: name, totalCoin: totalCoin, addCoin: addCoin, gameType: gameType, tick: d.getTime()};
    let info = JSON.stringify(obj);
    let listName = "winList_" + uid;
    yield  redis.lpushList(listName, info);
    yield  redis.keepListIn(listName, 0, cnst.keepWinRecordLen);

});


router.winCoinRecord_req = function (req, res) {
    let token = req.query.token;
    let totalCoin = req.query.totalCoin;
    let addCoin = req.query.addCoin;
    let sign = req.query.sign;
    let s1 = "token=" + token;
    let s2 = "totalCoin=" + totalCoin;
    let s3 = "addCoin=" + addCoin;
    let s4 = "checkSign=" + cnst.checkSign;
    let ss = [s1, s2, s3, s4];
    ss.sort(function (a, b) {
        if (a > b) return 1; else return -1;
    });
    let len = ss.length;
    let s = "";
    for (let i = 0; i < len; i++) {
        s = s + ss[i] + "&";
    }
    let md5 = Token.md5(s);
    if (md5 !== sign) {
        console.logg("invalid sign ", md5, sign);
        res.send({code: 500, msg: 'invalid sign'});
        return;
    }
};


router.get('/weixin/winCoinRecord', function (req, res) {

});

/*
router.post("/zadd", function (req, resp) {
    let coinRank = [{uid:100111333,rank:1,headimgurl:'http://imgcache.g9527.com/006zfdGjjw8fbhfdiu28zj30hs0h4gmb.jpg',coinNum:35200.79,viplv:4},
        {uid:10011223,rank:2,headimgurl:'http://imgcache.g9527.com/006zfdGjjw8fbhfdiu28zj30hs0h4gmb.jpg',coinNum:33897.39,viplv:4},
        {uid:13434223,rank:3,headimgurl:'http://imgcache.g9527.com/006zfdGjjw8fbhfdiu28zj30hs0h4gmb.jpg',coinNum:32133.21,viplv:3},
        {uid:12907521,rank:4,headimgurl:'http://imgcache.g9527.com/006zfdGjjw8fbhfdiu28zj30hs0h4gmb.jpg',coinNum:29224.07,viplv:3},
        {uid:12312333,rank:5,headimgurl:'http://imgcache.g9527.com/006zfdGjjw8fbhfdiu28zj30hs0h4gmb.jpg',coinNum:29111.30,viplv:3}];

    redis.selectDb(1);
    redis.del("coin_rank_list")
    for (let i = 0; i < coinRank.length; i++) {
        let item = coinRank[i]
        redis.zadd("coin_rank_list", item.rank, JSON.stringify(item));
    }

    let timeRank = [{uid:12312344111,rank:1,headimgurl:'http://imgcache.g9527.com/006zfdGjjw8fbhfdiu28zj30hs0h4gmb.jpg',time:'1299时',viplv:3},
        {uid:33435211,rank:2,headimgurl:'http://imgcache.g9527.com/006zfdGjjw8fbhfdiu28zj30hs0h4gmb.jpg',time:'1008时',viplv:2},
        {uid:23455551,rank:3,headimgurl:'http://imgcache.g9527.com/006zfdGjjw8fbhfdiu28zj30hs0h4gmb.jpg',time:'950时',viplv:3}];
    redis.del("time_rank_list")
    for (let i = 0; i < timeRank.length; i++) {
        let item = timeRank[i]
        redis.zadd("time_rank_list", item.rank, JSON.stringify(item));
    }

    let lvRank = [{uid:21131312222,rank:1,headimgurl:'http://imgcache.g9527.com/006zfdGjjw8fbhfdiu28zj30hs0h4gmb.jpg',lv:21,viplv:3},
        {uid:21131312,rank:2,headimgurl:'http://imgcache.g9527.com/006zfdGjjw8fbhfdiu28zj30hs0h4gmb.jpg',lv:21,viplv:4},
        {uid:53221231,rank:3,headimgurl:'http://imgcache.g9527.com/006zfdGjjw8fbhfdiu28zj30hs0h4gmb.jpg',lv:20,viplv:4},
        {uid:10999122,rank:4,headimgurl:'http://imgcache.g9527.com/006zfdGjjw8fbhfdiu28zj30hs0h4gmb.jpg',lv:20,viplv:3}];
    redis.del("lv_rank_list")
    for (let i = 0; i < lvRank.length; i++) {
        let item = lvRank[i]
        redis.zadd("lv_rank_list", item.rank, JSON.stringify(item));
    }

    resp.send({code:200, msg: "success"});
});
*/
router.post("/rank", function (req, resp) {
    rankService.getRankData().then(res => {
        resp.send({code: 200, msg: "success", data: res});
    }).catch(err => {
        console.logw("rank err:", err);
        resp.send({code: 500, msg: err});
    });
});
